package com.s59.rabc.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.s59.rabc.redis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.s59.rabc.commen.Constants.CACHE_PREFIX_TOKEN;

@Component
public class TokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if(StringUtils.hasText(token)){
            //从redis中找回用户
            String json = redisUtils.get(CACHE_PREFIX_TOKEN+token);
            UserDetailsimpl userDetailsimpl = new ObjectMapper().readValue(json,UserDetailsimpl.class);
            //存储userDelails到ss的上下文中
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(userDetailsimpl,userDetailsimpl.getPassword(),userDetailsimpl.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request,response);
    }
}
